package com.jsb.laundry.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.jsb.laundry.common.utils.aliyun.AliOSSUtil;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

/**
 * 二维码生成工具类
 */
public class QRCodeUtil {

    private static final String CHARSET = "utf-8";

    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;

    public static BufferedImage createImage(String content) {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
                    hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }


    /**
     * 默认二维码宽度
     */
    private static final int DEFAULT_QR_CODE_WIDTH = 300;

    /**
     * 默认二维码高度
     */
    private static final int DEFAULT_QR_CODE_HEIGHT = 300;

    /**
     * base64前缀
     */
    private static final String BASE64_PREFIX = "data:image/bmp;base64,";

    /**
     * 设置二维码参数
     */
    private static final Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {{
        put(EncodeHintType.CHARACTER_SET, "utf-8");
        put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        put(EncodeHintType.MARGIN, 1);
    }};

    /**
     * 获取二维码图片
     *
     * @param codeValue 二维码内容
     * @return 二维码图片
     */
    public static BufferedImage getQRCodeImage(String codeValue) {
        return getQRCodeImage(codeValue, DEFAULT_QR_CODE_WIDTH, DEFAULT_QR_CODE_HEIGHT);
    }

    /**
     * 获取二维码图片
     *
     * @param codeValue 二维码内容
     * @param width     宽度
     * @param height    高度
     * @return 二维码图片
     */
    public static BufferedImage getQRCodeImage(String codeValue, int width, int height) {
        // 编码内容, 编码类型, 宽度, 高度, 设置参数
        BitMatrix bitMatrix;
        try {
            bitMatrix = new MultiFormatWriter().encode(codeValue, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException e) {
            throw new RuntimeException("二维码内容写入失败");
        }
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }

    /**
     * 获取带logo的二维码图片
     *
     * @param codeValue  二维码内容
     * @param logoFile   logo文件
     * @param logoWidth  logo宽度
     * @param logoHeight logo高度
     * @return 带logo的二维码图片
     */
    public static BufferedImage getQRCodeImageWithLogo(String codeValue, File logoFile, int logoWidth, int logoHeight) {
        BufferedImage qrCodeImage = getQRCodeImage(codeValue);
        BufferedImage logoImage = null;
        try {
            logoImage = ImageIO.read(logoFile);
        } catch (IOException e) {
            throw new RuntimeException("logo文件读取失败");
        }
        // 将qrCodeImage转换为ARGB类型
        BufferedImage argbQrCodeImage = new BufferedImage(qrCodeImage.getWidth(), qrCodeImage.getHeight(), BufferedImage.TYPE_INT_BGR);
        Graphics2D g2d = argbQrCodeImage.createGraphics();
        g2d.drawImage(qrCodeImage, 0, 0, null);
        g2d.dispose();
        qrCodeImage = argbQrCodeImage;
        g2d = qrCodeImage.createGraphics();

        // 抗锯齿
        setGraphics2D(g2d);
        // logo默认居中显示
        int logoStartX = (qrCodeImage.getWidth() - logoWidth) / 2;
        int logoStartY = (qrCodeImage.getHeight() - logoHeight) / 2;

        g2d.drawImage(logoImage, logoStartX, logoStartY, logoWidth, logoHeight, null);
        g2d.dispose();
        qrCodeImage.flush();
        return qrCodeImage;
    }

    /**
     * 设置 Graphics2D 属性 （抗锯齿）
     *
     * @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setGraphics2D(Graphics2D g2d) {
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
        g2d.setStroke(s);
    }

    /**
     * 文件流转MultipartFile
     *
     * @param image
     * @return
     * @throws IOException
     */
    public static MultipartFile convertToMultipartFile(BufferedImage image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", baos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        byte[] bytes = baos.toByteArray();
        return new MultipartFile() {
            @Override
            public String getName() {
                return "image.jpg";
            }

            @Override
            public String getOriginalFilename() {
                return "image.jpg";
            }

            @Override
            public String getContentType() {
                return "image/jpeg";
            }

            @Override
            public boolean isEmpty() {
                return bytes.length == 0;
            }

            @Override
            public long getSize() {
                return bytes.length;
            }

            @Override
            public byte[] getBytes() {
                return bytes;
            }

            @Override
            public InputStream getInputStream() {
                return new ByteArrayInputStream(bytes);
            }

            @Override
            public void transferTo(File file) throws IOException, IllegalStateException {
                new FileOutputStream(file).write(bytes);
            }
        };
    }

    /**
     * MultipartFile直接转base64
     *
     * @param multiPartFile
     * @return
     */
    public static String getBase64String(MultipartFile multiPartFile) {
        String baseStr = null;
        try {
            baseStr = Base64.getEncoder().encodeToString(multiPartFile.getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        baseStr = baseStr.replaceAll("\r\n", "");
        return BASE64_PREFIX + baseStr;
    }

    /**
     * 测试到OSSTest中testQR1
     * @param args
     */
    public static void main(String[] args) {
        BufferedImage image = QRCodeUtil.getQRCodeImage("http://www.jsbjtx.com/jxy.apk");
        MultipartFile multipartFile = QRCodeUtil.convertToMultipartFile(image);
        String base64String = getBase64String(multipartFile);
        String path = AliOSSUtil.uploadFile(multipartFile, "laundry/qrcode");
        System.out.println(base64String);
    }

}

